
#include <iostream>
#include <memory>
#include <string>

// 状态接口
class OrderState {
public:
    virtual ~OrderState() = default;
    virtual void handleOrder() = 0;   // 处理订单的方法
    virtual void nextState(class OrderContext& context) = 0; // 进入下一个状态
};

// 上下文类
class OrderContext {
private:
    std::shared_ptr<OrderState> state_; // 当前状态

public:
    explicit OrderContext(std::shared_ptr<OrderState> state) : state_(state) {}

    void setState(const std::shared_ptr<OrderState>& state) {
            state_ = state;
    }

    void handleOrder() {
            state_->handleOrder();
    }

    void nextState() {
            state_->nextState(*this);
    }
};

// 具体状态：新建订单
class NewOrderState : public OrderState {
public:

    void handleOrder() override {
            std::cout << "Order is new and waiting for payment.\n";
    }

    void nextState(OrderContext& context) override;
};

// 具体状态：已支付
class PaidOrderState : public OrderState {
public:
    void handleOrder() override {
            std::cout << "Order has been paid and is waiting to be shipped.\n";
    }

    void nextState(OrderContext& context) override;
};

// 具体状态：已发货
class ShippedOrderState : public OrderState {
public:

    void handleOrder() override {
            std::cout << "Order has been shipped and is on its way to the customer.\n";
    }

    void nextState(OrderContext& context) override;
};

// 具体状态：已完成
class CompletedOrderState : public OrderState {
public:
    void handleOrder() override {
            std::cout << "Order has been delivered and completed.\n";
    }

    void nextState(OrderContext&) override {
            std::cout << "Order is already completed. No further states.\n";
    }
};

// 状态转换实现
void NewOrderState::nextState(OrderContext& context) {
    context.setState(std::make_shared<PaidOrderState>());
    std::cout << "Order state changed to: Paid\n";
}

void PaidOrderState::nextState(OrderContext& context) {
    context.setState(std::make_shared<ShippedOrderState>());
    std::cout << "Order state changed to: Shipped\n";
}

void ShippedOrderState::nextState(OrderContext& context) {
    context.setState(std::make_shared<CompletedOrderState>());
    std::cout << "Order state changed to: Completed\n";
}

// 客户端代码
int main() {
    // 创建初始状态
    auto newOrderState = std::make_shared<NewOrderState>();
    OrderContext order(newOrderState);

    // 按顺序处理订单状态
    order.handleOrder();
    order.nextState();

    order.handleOrder();
    order.nextState();

    order.handleOrder();
    order.nextState();

    order.handleOrder();
    order.nextState(); // 无法再进入下一个状态

    return 0;
}